package com.orangelife.mobile.main.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.sp.UserSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.main.biz.JumpUtil;
import com.thirdsdk.umeng.UMShare;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.util.UriUtil;
import com.orangelife.mobile.widget.SelectPicPopupWindowView;
import com.orangelife.mobile.web.WebWin;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.bean.StatusCode;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;

import java.util.HashMap;
import java.util.Map;
@Deprecated
public class AdShow extends OrangeLifeBaseActivity {
    /** 广告详情标题 */
    private TextView tvTitle;
    /** 标题右边 */
    private ImageView ivTitleRight;
    /** 详情展示 */
    private WebWin wwDesc;

    private String advertID = null;
    private int type = 1;
    /** 广告URL */
    private String adUrl = null;
    /** 是否显示分享按钮的广告类型 */
    private String advertType = null;
    /** 分享弹出框 */
    SelectPicPopupWindowView menuWindow;
    private SHARE_MEDIA platform;
    private UMShare share;
    /** 分享url */
    private String targetUrl = "http://www.com";/* 必须为http连接 */
    /** 分享title */
    private String uMtitle = "";
    /** 推送title */
    private String jPtitle = "";
    /** 分享content */
    private String uMcontent = "";
    private Dialog dialog;
    /** 首先在您的Activity中添加如下成员变量 */
    private final UMSocialService mController = UMServiceFactory
            .getUMSocialService("com.umeng.share");
    /** 广告分享标题 */
    private String title;
    /** 广告分享内容 */
    private String content;
    /** 分享获得积分的ID */
    private String linkID = null;
    private boolean isLoadUrl = false;
    private String body = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ad_show);
        share = UMShare.getInstance();
        share.setUMSS(mController, AdShow.this);
        share.configPlatforms();
        initeView();
        findView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        BLog.getInstance().inAdverDetail(advertID, type);
    }

    @Override
    protected void onStop() {
        super.onStop();
        BLog.getInstance().outAdverDetail(advertID, type);
    }

    private void initeView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        ivTitleRight = (ImageView) findViewById(R.id.iv_title_right);
        wwDesc = (WebWin) findViewById(R.id.wvDesc);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void findView() {
        Intent data = getIntent();
        Bundle desc = data.getExtras();
        type = desc.getInt("type");
        advertID = desc.getString("advertID");
        adUrl = UriUtil.replaceUri(this, desc.getString("url"));
        advertType = desc.getString("advertType");
        title = desc.getString("title");
        content = desc.getString("content");
        linkID = desc.getString("linkID");
        body = desc.getString("body");
        tvTitle.setText(title);
        if (advertType != null) {
            if ("5".equals(advertType)) {
                ivTitleRight.setBackgroundResource(R.drawable.share1);
            } else {
                ivTitleRight.setVisibility(View.GONE);
            }
        }
        if (!StringUtil.isBlank(title)) {
            jPtitle = title;
            uMtitle = title;
            if (content == null) {
                uMcontent = title;
            } else {
                uMcontent = content;
            }
        } else {
            jPtitle = "广告详情";
            uMtitle = "橙子生活";
            uMcontent = "橙子生活";
        }
        tvTitle.setText(jPtitle);
        ivTitleRight.setOnClickListener(listener);
        wwDesc.loadUrl(adUrl);
        wwDesc.getSettings().setJavaScriptEnabled(true);
        wwDesc.getSettings().setCacheMode(wwDesc.getSettings().LOAD_DEFAULT);
        wwDesc.addJavascriptInterface(new ScriptInterface(), "orangelife");
    }

    class ScriptInterface {
        @android.webkit.JavascriptInterface
        public void share(String url) {
            Uri uri = Uri.parse(url);
            if (uri.getScheme().equals("orangelife")
                    && uri.getHost().equals("www.com")) {
//				ExplainUrlUtils.explainUrl(uri, AdShow.this,true);
                JumpUtil.jumpActivity(AdShow.this, url, true);
            } else {
                wwDesc.loadUrl(url);
            }
        }
    }


    private OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.iv_title_right:
                /* 实例化SelectPicPopupWindow */
                    menuWindow = new SelectPicPopupWindowView(AdShow.this,
                            itemsOnClick);
				/* 显示窗口 */
                    menuWindow.showAtLocation(AdShow.this.findViewById(R.id.main),
                            Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    break;

                default:
                    break;
            }
        }
    };

    /** 为弹出窗口实现监听类 */
    private OnClickListener itemsOnClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.ib_pengyouquan:
                    platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                    break;
                case R.id.ib_qq:
                    platform = SHARE_MEDIA.QQ;
                    break;
                case R.id.ib_weibo:
                    platform = SHARE_MEDIA.SINA;
                    break;
                case R.id.ib_weixin:
                    platform = SHARE_MEDIA.WEIXIN;
                    break;
                default:
                    break;
            }
            UmengShare();

        }

    };

    private void UmengShare() {
        if (adUrl.indexOf("?") == -1) {
            targetUrl = adUrl + "?type=share";
        } else {
            targetUrl = adUrl + "&type=share";
        }
        share.setShareInfo(uMtitle, uMcontent, targetUrl);
        share.setShare(platform);
        mController.postShare(AdShow.this, platform, new SnsPostListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int eCode,
                                   SocializeEntity entity) {
            }
        });
		/* 分享回调 */
        mController.getConfig().registerListener(
                new SocializeListeners.SnsPostListener() {
                    @Override
                    public void onStart() {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(
                                        R.string.share_begin_toast));
                    }

                    @Override
                    public void onComplete(SHARE_MEDIA platform, int eCode,
                                           SocializeEntity entity) {
                        if (eCode == StatusCode.ST_CODE_SUCCESSED) {
                            String type = whatType(platform.ordinal());
                            getScoll(linkID, type);
                        }
                    }
                });
    }

    /**
     * @param type 分享的平台 4 新浪微博 ；5 QQ空间 ；6 QQ； 8 微信 ； 9 微信朋友圈
     * @return 1 微信分享商户;2 微博分享商户;3 QQ分享商户;
     */
    private String whatType(int type) {
        String t = "";
        switch (type) {
            case 4:
                t = "2";
                break;
            case 6:
                t = "3";
                break;
            case 5:
                t = "3";
                break;
            case 8:
                t = "1";
                break;
            case 9:
                t = "4";
            default:
                break;
        }
        return t;
    }

    /**
     * 积分
     */
    private void getScoll(String merId, String shareType) {
        Map<String, Object> mapSubmit = new HashMap<String, Object>();
        mapSubmit.put("merID", merId);
        mapSubmit.put("type", "9");/* 专题分享 */
        mapSubmit.put("scoreType", shareType);/* 1 微信分享商户;2 微博分享商户;3 QQ分享商户 */
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", mapSubmit);
        rootMap.put("url", Constant.URL_ADD_SCORE);
        rootMap.put("wat", 1);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    /**
     * 处理返回的信息数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 500:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                case 1011:
                    isLogin(dialog, AdShow.this);
                    break;
                case 1:
				/*
				 * 返回参数 "scoreResult": "0", "score": "15", "scoreExchange": "1",
				 * "sponit":"5"
				 */
                    final Map<String, Object> map = (Map<String, Object>) JSONHelper
                            .jsonToMap(msg.obj.toString()).get("entity");
                    if (map != null) {
                        String scoreResult = map.get("scoreResult").toString();
                        String sponit = map.get("sponit").toString();
                        if (scoreResult.equals("0")) {
                            UserSp.setPoint(String.valueOf(map.get("score")));
                            if (!StringUtil.isBlank(UserSp.getLoginID())) {
                                ToastHelper.getInstance()._toast(
                                        "恭喜您获得了" + sponit + "积分");
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }

    };

}
